/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.evaluation;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.SecurityDocumentDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.SecurityDocumentRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.SecurityDocumentMapper;
import cn.ac.nercis.pes.repository.model.evaluation.SecurityDocumentDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 安全管理文档信息服务类
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class SecurityDocumentService {

    private final SecurityDocumentRepository securityDocumentRepository;

    @Autowired
    public SecurityDocumentService(SecurityDocumentRepository securityDocumentRepository) {
        this.securityDocumentRepository = securityDocumentRepository;
    }

    public List<SecurityDocumentDTO> findSecurityDocument(String systemId){
        return this.securityDocumentRepository.findAllBySystemId(systemId)
                .stream()
                .map(SecurityDocumentMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
    }

    public Result<SecurityDocumentDTO> saveSecurityDocument(SecurityDocumentDTO securityDocument){
        if(StringUtils.isEmpty(securityDocument.getName())){
            securityDocument.setName("");
        }
        if(StringUtils.isEmpty(securityDocument.getContent())){
            securityDocument.setContent("");
        }
        try{
            if(StringUtils.isEmpty(securityDocument.getId())){
                return create(securityDocument);
            }else{
                return modify(securityDocument);
            }
        }catch (Exception e){
            log.error("保存安全管理文档信息出错：",e);
            return Result.failed();
        }
    }

    public Result<String> batchSaveSecurityDocument(List<SecurityDocumentDTO> data){
        Result<String> result = Result.success();
        for(SecurityDocumentDTO item : data){
            Result<SecurityDocumentDTO> itemResult = saveSecurityDocument(item);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public Result<String> deleteSecurityDocument(String id){
        try{
            return this.securityDocumentRepository.findById(id)
                    .map(securityDocumentDO -> {
                        securityDocumentRepository.delete(securityDocumentDO);
                        return securityDocumentDO;
                    })
                    .map(SecurityDocumentDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除安全管理文档信息出错：",ex);
            return Result.failed();
        }
    }

    public Result<String> batchDeleteSecurityDocument(Set<String> ids){
        Result<String> result = Result.success();
        for(String id : ids){
            Result<String> itemResult = deleteSecurityDocument(id);
            if(!itemResult.isSuccess()){
                result = itemResult;
                break;
            }
        }
        return result;
    }

    private Result<SecurityDocumentDTO> create(SecurityDocumentDTO securityDocument){
        return Optional.of(SecurityDocumentMapper.INSTANCE.toDO(securityDocument))
                .map(e->{
                    e.setCreateTime(LocalDateTime.now());
                    return e;
                })
                .map(securityDocumentRepository::save)
                .map(SecurityDocumentMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<SecurityDocumentDTO> modify(SecurityDocumentDTO securityDocument){
        SecurityDocumentDO source = this.securityDocumentRepository.findById(securityDocument.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    s.setName(securityDocument.getName());
                    s.setContent(securityDocument.getContent());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(securityDocumentRepository::save)
                .map(SecurityDocumentMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed(ResultCode.FAIL));
    }

}